const mqtt = require('mqtt');
const client = mqtt.connect(require('../config/mqtt.config').broker);

exports.controlDevice = async (deviceId, command) => {
  const device = await Device.findByPk(deviceId);
  if (!device) throw new Error('设备不存在');

  // 通过MQTT下发指令
  client.publish(`device/${deviceId}/cmd`, JSON.stringify(command));

  // 记录操作日志
  await OperationLog.create({
    user_id: req.user.id,
    device_id: deviceId,
    action: 'control',
    detail: command
  });
};